// 使用 multer 处理文件上传
const multer = require('multer');
const { v4: uuid } = require('uuid');
const path = require('path');
// 配置上传文件的存储位置和文件名
const genStorage = (pathname) => {
	return multer.diskStorage({
		destination: function (req, file, cb) {
			cb(null, pathname);
		},
		filename: function (req, file, cb) {
			const ext = path.extname(file.originalname);
			cb(null, uuid() + ext);
		}
	});
};

// 自定义配置上传文件的存储位置和文件名
const customGenStorage = (pathname) => {
	return multer.diskStorage({
		destination: function (req, file, cb) {
			let uploadPath = pathname;
			if (file.fieldname === 'icon') {
				uploadPath = pathname + '/pictures';
			} else if (file.fieldname === 'files') {
				uploadPath = pathname + '/files';
			}
			cb(null, uploadPath);
		},
		filename: function (req, file, cb) {
			const ext = path.extname(file.originalname);
			cb(null, uuid() + ext);
		}
	});
};

const avatar = multer({ storage: genStorage('./public/avatars') }),
	picture = multer({ storage: genStorage('./public/pictures') }),
	logo = multer({ storage: genStorage('./public/logos') }),
	bankcard = multer({ storage: genStorage('./public/bankcards') }),
	file = multer({ storage: genStorage('./public/files') }),
	customUpload = multer({ storage: customGenStorage('./public') });

module.exports = { avatar, picture, logo, bankcard, file, customUpload };
